# -*- coding: cp936 -*-
import socket, select, sys
import time
from random import Random

def random_str(randomlength=8):
	str = ''
	chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
	length = len(chars) - 1
	random = Random()
	for i in range(randomlength):
		str+=chars[random.randint(0, length)]
	return str

sock = socket.socket(socket.AF_INET ,socket.SOCK_STREAM, 0)
address=('192.168.1.151', 50001)
sock.connect(address)

epoll = select.epoll()
epoll.register(sock.fileno(), select.EPOLLIN)
epoll.register(0, select.EPOLLIN)

sock.send('\x00D')

count = 0

while True:
	events = epoll.poll(1)
	for fileno, event in events:
		if fileno == 0:
			print 'stdin'
			str_input = raw_input()
			randstr = random_str(int(str_input))
			#randstr = randstr + '\x7e'
			print ''.join(['\\x%02x' % ord(x) for x in randstr])
			sock.send(randstr )
			#sock.send('\x02\x00\x00\x00\x34\x00\x55\x00\x00\x00\x71\x00\x00\x00\x00\x00\x00\x00\x00')
			#time.sleep(0.1)
		elif fileno == sock.fileno():
			buff = sock.recv(8192)
			if len(buff) == 0:
				sock.close()
				epoll.unregister(fileno)
			count+=len(buff)
			print count
			print ''.join(['\\x%02x' % ord(x) for x in buff]) 
